package com.bafa.front.events;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.sql.PreparedStatement;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.bafa.debug.Debug;
import com.bafa.jdbc.DBAccess;
import com.bafa.objects.PageBean;
import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.media.MediaFileSource;
import com.google.gdata.data.media.mediarss.MediaThumbnail;
import com.google.gdata.data.photos.PhotoEntry;

public class UploadPhotoEvent extends Event {

	@Override
	public void doEvent(HttpServletRequest request,
			HttpServletResponse response, PageBean page) {
//		 Create a factory for disk-based file items
		FileItemFactory factory = new DiskFileItemFactory();

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			// Parse the request
			List items = upload.parseRequest(request);

			Iterator iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.getName().indexOf("jpg") > 1 ||item.getName().indexOf("gif") > 1||item.getName().indexOf("png") > 1) {
				InputStream uploadedStream = item.getInputStream();
			    File file = new File("temp.jpg");
				item.write(file);
			    
				PicasawebService myService = new PicasawebService("bafa-test-2");
				myService.setUserCredentials("r.hmeid@gmail.com", "socrat3s");

				URL postUrl =
				  new URL("http://picasaweb.google.com/data/feed/api/user/r.hmeid/album/bafa");
				  // Send the request for the album's photos.

				PhotoEntry myPhoto = new PhotoEntry();
				myPhoto.setTitle(new PlainTextConstruct(request.getParameter("photoname")));
				myPhoto.setDescription(new PlainTextConstruct(request.getParameter("photoname")));
				myPhoto.setClient("OR Rovers");
				myPhoto.setTimestamp (new Date());
				MediaFileSource myMedia = new MediaFileSource(file, "image/jpeg");
				myPhoto.setMediaSource(myMedia);
				Debug.debug(this.getClass(),"doEvent","MATCH ID: "+request.getParameter("matchId"));
				Debug.debug(this.getClass(),"doEvent","TEAM ID: "+request.getParameter("teamId"));
				Debug.debug(this.getClass(),"doEvent","MY PHOTO NAME: "+request.getParameter("photoname"));
				Debug.debug(this.getClass(),"doEvent","MY PHOTO TITLE: "+myPhoto.getTitle().getPlainText());
				
				PhotoEntry returnedPhoto = myService.insert(postUrl, myPhoto);
				Debug.debug(this.getClass(),"doEvent","VERSION: "+returnedPhoto.getAdaptedEntry().getVersionId());
				List thumbnails = returnedPhoto.getMediaThumbnails();

				MediaThumbnail media = (MediaThumbnail)thumbnails.get(thumbnails.size()-1);
				
				PreparedStatement updateTeam = new DBAccess().conn.prepareStatement("insert into photos values(?,?,?,?,?,?,?)");
		        updateTeam.setString(4, media.getUrl());  
				updateTeam.setString(6, returnedPhoto.getGphotoId());
				updateTeam.setString(7, returnedPhoto.getVersion()+""); 
		        updateTeam.setString(1, request.getParameter("photoname"));
				updateTeam.setInt(2, new Integer(request.getParameter("teamId")));
				updateTeam.setInt(3, new Integer(request.getParameter("matchId")));
				updateTeam.setDate(5, new java.sql.Date(new Date().getTime()));
		        updateTeam.executeUpdate();
			}else{
				message.addError("Invalid file format.");
			}
			}
		}catch(Exception e){
			Debug.printStackTrace(e);
		}
	}

}
